import { _decorator, Component, Node, Button, Label, Vec3 } from 'cc';
import { BasePanel } from '../../../../scripts/libs/ui/BasePanel';
import { ReactiveProperty } from '../../../../scripts/libs/rxjs/cc3/ReactiveProperty';
import { DevConfig } from '../../../../scripts/managers/DevConfig';
import { udm } from '../../../../scripts/managers/UserDataManager';
import { thinking_sdk_m } from '../../../../scripts/managers/SDK/ThinkingCocosSDKManager';
import { StageInfo } from '../../game/basic';
import { randomChooseWithProb } from '../../../../scripts/libs/utils/RandomChooseTools';
import { BindButton } from '../../../../scripts/libs/rxjs/cc3/BindButton';
import { MergeASAP } from '../../../../scripts/libs/rxjs/cc3/Merge';
import { ProvideInfo } from '../../../../scripts/managers/SDK/IapSDKManager';
import { find } from 'cc';
import { UIOpacity } from 'cc';
import { forkJoin, Observable, of, Subscription } from 'rxjs';
import { nullifySubscription } from '../../../../scripts/libs/rxjs/utils';
import { sp } from 'cc';
import { SkeletonPlay } from '../../../../scripts/libs/rxjs/cc3/SkeletonPlay';
import { v3 } from 'cc';
import { JumpTo_2D, TweenToStart } from '../../../../scripts/libs/rxjs/cc3/TweenStart';
import { lm } from '../../LobbyManager';
import { am } from '../../../../scripts/managers/AudioManager';
const { ccclass, property } = _decorator;

@ccclass('ChestOpenPanel')
export class ChestOpenPanel extends BasePanel {

    stageInfo = ReactiveProperty.Create<StageInfo>(null);
    key = ReactiveProperty.Create<string>(null);

    @property(Node)
    mainNode: Node = null;

    @property(sp.Skeleton)
    kaixiang: sp.Skeleton = null;

    @property(Button)
    claimButton: Button = null;

    @property(Node)
    provideNode: Node = null;

    willBind(): void {
        this.claimButton.interactable = false;
        this.claimButton.node.active = false;
        this.claimButton.getComponent(UIOpacity).opacity = 0;
        this.adaptive();
    }

    useObserves() {
        return [
            MergeASAP(this.key, this.stageInfo).subscribe(this.refresh.bind(this)),
            BindButton(this.claimButton).subscribe(this.claimButtonClicked.bind(this)),
        ];
    }

    adaptive() {
        this.mainNode.setScale(v3(Vec3.ONE).multiplyScalar(lm.getAdaptiveScale()));
    }

    afterOpen(): Observable<string> {
        this.burstAnim();
        return of();
    }

    refresh() {
        if (this.key.value == null || this.stageInfo.value == null) return;
        udm.stageChest.value = null;
        if (this.key.value == 'stage2') {
            // this.contentLabel.string = JSON.stringify(DevConfig.STAGE_CHEST.stage2.provide);
            this.refreshProvide(DevConfig.STAGE_CHEST.stage2.provide);
            udm.provide(DevConfig.STAGE_CHEST.stage2.provide);
            udm.temp_coin_diff.value = DevConfig.STAGE_CHEST.stage2.provide.coin ?? 0;
            this.thinking(DevConfig.STAGE_CHEST.stage2.provide, 'LevelBox');
        } else if (this.key.value == 'stage5') {
            // this.contentLabel.string = JSON.stringify(DevConfig.STAGE_CHEST.stage5.provide);
            this.refreshProvide(DevConfig.STAGE_CHEST.stage5.provide);
            udm.provide(DevConfig.STAGE_CHEST.stage5.provide);
            udm.temp_coin_diff.value = DevConfig.STAGE_CHEST.stage5.provide.coin ?? 0;
            this.thinking(DevConfig.STAGE_CHEST.stage5.provide, 'LevelBox');
        } else if (this.key.value == 'stageMod5') {
            let probability = DevConfig.STAGE_CHEST.stageMod5.probability;
            let result = randomChooseWithProb(probability, 'p');
            // this.contentLabel.string = JSON.stringify(result.provide);
            this.refreshProvide(result.provide);
            udm.provide(result.provide);
            this.thinking(result.provide, 'LevelBox');
        } else if (this.key.value == 'daily_total') {
            let probability = DevConfig.TASK_DAILY_CHEST.daily_total.probability;
            let result = randomChooseWithProb(probability, 'p');
            // this.contentLabel.string = JSON.stringify(result.provide);
            this.refreshProvide(result.provide);
            udm.provide(result.provide);
            this.thinking(result.provide, 'DailyTaskBox');
        }
    }

    refreshProvide(provide: ProvideInfo) {
        for (let i = 0; i < this.provideNode.children.length; i++) {
            let node = this.provideNode.children[i];
            if (node.name == 'coin') {
                if (provide.coin > 0) {
                    node.active = true;
                    node.getComponent(UIOpacity).opacity = 0;
                    find('coin/normal/Label', this.provideNode).getComponent(Label).string = `${provide.coin}`;
                } else {
                    node.active = false;
                    find('coin/normal/Label', this.provideNode).getComponent(Label).string = '0';
                }
            }
            if (node.name == 'swapper') {
                if (provide.swapper > 0) {
                    node.active = true;
                    node.getComponent(UIOpacity).opacity = 0;
                    find('swapper/normal/Label', this.provideNode).getComponent(Label).string = `${provide.swapper}`;
                } else {
                    node.active = false;
                    find('swapper/normal/Label', this.provideNode).getComponent(Label).string = '0';
                }
            }
            if (node.name == 'magnet') {
                if (provide.magnet > 0) {
                    node.active = true;
                    node.getComponent(UIOpacity).opacity = 0;
                    find('magnet/normal/Label', this.provideNode).getComponent(Label).string = `${provide.magnet}`;
                } else {
                    node.active = false;
                    find('magnet/normal/Label', this.provideNode).getComponent(Label).string = '0';
                }
            }
            if (node.name == 'balloon') {
                if (provide.balloon > 0) {
                    node.active = true;
                    node.getComponent(UIOpacity).opacity = 0;
                    find('balloon/normal/Label', this.provideNode).getComponent(Label).string = `${provide.balloon}`;
                } else {
                    node.active = false;
                    find('balloon/normal/Label', this.provideNode).getComponent(Label).string = '0';
                }
            }
        }
    }

    burstAnim() {
        SkeletonPlay(this.kaixiang, 'kaixiang', false).subscribe(_ => {
            this.log('SkeletonPlay next:', _);
            if (_.state == 'event' && _.event.data.name == 'burst') {
                let list: Observable<any>[] = [];
                for (let i = 0; i < this.provideNode.children.length; i++) {
                    let node = this.provideNode.children[i];
                    if (node.active) {
                        let targetPos = v3(node.position);
                        node.setWorldPosition(this.kaixiang.node.worldPosition);
                        let obs = forkJoin([
                            JumpTo_2D(node, .6, targetPos, 400, { easing: 'quadInOut' }),
                            TweenToStart(node.getComponent(UIOpacity), .2, { opacity: 255 }),
                        ]);
                        list.push(obs);
                    }
                }
                forkJoin(list).subscribe({
                    complete: () => {
                        this.claimButton.node.active = true;
                        TweenToStart(this.claimButton.getComponent(UIOpacity), .2, { opacity: 255 }).subscribe({
                            complete: () => {
                                this.claimButton.interactable = true;
                            }
                        }).addTo(this.node);
                    }
                }).addTo(this.node);
                am.playSfx({ clipName: `ab_lobby/Audio/sfx/kaixiang` });

            }
        }).addTo(this.node);
    }

    claimButtonClicked() {
        ChestOpenPanel.CloseProcess(null, 'close');
    }

    thinking(provide: ProvideInfo, type: string) {
        if (provide.coin > 0) {
            udm.temp_coin_diff.value = provide.coin ?? 0;
            thinking_sdk_m.requestTrack('Coins_Get', {
                CoinNum: provide.coin,
                Type: type,
                Gift_Detail: 'Other',
                IsNew: udm.isNew.value,
                Level_ID: this.stageInfo.value.stageId,
                Booster_Itemdetail: `Swapper:${udm.itemSwapper.value}|Magnet:${udm.itemMagnet.value}|Balloon:${udm.itemBalloon.value}`
            });
        } else if (provide.swapper > 0) {
            thinking_sdk_m.requestTrack('Item_Get', {
                ItemType: 'swapper',
                CType: type,
                UseType: 'Num',
                ItemNum: provide.swapper,
                ItemAll: udm.itemSwapper.value,
                Level_ID: this.stageInfo.value.stageId,
                IsNew: udm.isNew.value,
                Booster_Itemdetail: `Swapper:${udm.itemSwapper.value}|Magnet:${udm.itemMagnet.value}|Balloon:${udm.itemBalloon.value}`
            });
        } else if (provide.magnet > 0) {
            thinking_sdk_m.requestTrack('Item_Get', {
                ItemType: 'magnet',
                CType: type,
                UseType: 'Num',
                ItemNum: provide.magnet,
                ItemAll: udm.itemMagnet.value,
                Level_ID: this.stageInfo.value.stageId,
                IsNew: udm.isNew.value,
                Booster_Itemdetail: `Swapper:${udm.itemSwapper.value}|Magnet:${udm.itemMagnet.value}|Balloon:${udm.itemBalloon.value}`
            });
        } else if (provide.balloon > 0) {
            thinking_sdk_m.requestTrack('Item_Get', {
                ItemType: 'balloon',
                CType: type,
                UseType: 'Num',
                ItemNum: provide.balloon,
                ItemAll: udm.itemBalloon.value,
                Level_ID: this.stageInfo.value.stageId,
                IsNew: udm.isNew.value,
                Booster_Itemdetail: `Swapper:${udm.itemSwapper.value}|Magnet:${udm.itemMagnet.value}|Balloon:${udm.itemBalloon.value}`
            });
        }
        // TODO: 如果关卡宝箱里面有体力的奖励，也应该在此补充
    }
}

